package org.groupg.practice.swingx;

import com.formdev.flatlaf.FlatIntelliJLaf;
import org.jdesktop.swingx.JXDatePicker;
import org.jdesktop.swingx.JXFrame;
import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.table.DatePickerCellEditor;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SwingXDemo {

    public static void main(String[] args) throws UnsupportedLookAndFeelException {

        UIManager.setLookAndFeel(new FlatIntelliJLaf());

        // 创建 JXFrame（增强版的 JFrame）
        JXFrame frame = new JXFrame("SwingX 组件演示");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
        frame.setLayout(new BorderLayout(10, 10));

        // 1. JXDatePicker 示例
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        JXDatePicker datePicker = new JXDatePicker(new Date());
        datePicker.setFormats(new SimpleDateFormat("yyyy-MM-dd"));

        JButton showDateButton = new JButton("显示选中日期");
        topPanel.add(new JLabel("选择日期:"));
        topPanel.add(datePicker);
        topPanel.add(showDateButton);

        frame.add(topPanel, BorderLayout.NORTH);

        // 2. JXTable 示例（带日期列）
        String[] columns = {"姓名", "入职日期", "薪资"};
        Object[][] data = {
                {"张三", new Date(), 8500.00},
                {"李四", new Date(), 9200.00},
                {"王五", new Date(), 7800.00}
        };

        DefaultTableModel model = new DefaultTableModel(data, columns);
        JXTable table = new JXTable(model);

        // 获取日期列（第二列，索引为1）
        TableColumn dateColumn = table.getColumnModel().getColumn(1);
        // 创建自定义的日期渲染器
        DateRenderer dateRenderer = new DateRenderer("yyyy-MM-dd");
        // 将该渲染器设置到日期列上
        dateColumn.setCellRenderer(dateRenderer);

        // 设置日期列使用 JXDatePicker 作为编辑器
        dateColumn.setCellEditor(new DatePickerCellEditor(new SimpleDateFormat("yyyy-MM-dd")));

        // 启用表格增强功能：排序、过滤等
        table.setSortable(true);
        table.packAll();

        JScrollPane scrollPane = new JScrollPane(table);
        frame.add(scrollPane, BorderLayout.CENTER);

        // 按钮事件处理
        showDateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Date selectedDate = datePicker.getDate();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                JOptionPane.showMessageDialog(frame,
                        "选中的日期: " + sdf.format(selectedDate),
                        "日期选择",
                        JOptionPane.INFORMATION_MESSAGE);
            }
        });

        // 显示窗口
        frame.setVisible(true);
    }
}